package com.example.smartmedicalsystem.controller;

import com.example.smartmedicalsystem.entity.*;
import com.example.smartmedicalsystem.repository.*;
import lombok.RequiredArgsConstructor;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.Authentication;
import org.springframework.web.bind.annotation.*;
import org.springframework.security.crypto.password.PasswordEncoder;
import java.time.LocalDate;
import java.util.List;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/patient")
@RequiredArgsConstructor
public class PatientController {
    private final UserRepository userRepository;
    private final DoctorRepository doctorRepository;
    private final ScheduleRepository scheduleRepository;
    private final AppointmentRepository appointmentRepository;
    private final DepartmentRepository departmentRepository;
    private final PasswordEncoder passwordEncoder;
    private final MessageRepository messageRepository;
    private final MedicineRepository medicineRepository;
    private final UserMedicineRepository userMedicineRepository;

    @PostMapping("/register")
    public ResponseEntity<?> register(@RequestBody User user) {
        if (userRepository.findByUsername(user.getUsername()) != null) {
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("用户名已存在");
        }
        user.setRole(User.Role.PATIENT);
        user.setPassword(passwordEncoder.encode(user.getPassword()));
        User savedUser = userRepository.save(user);
        return ResponseEntity.ok(savedUser);
    }

    @GetMapping("/departments")
    public ResponseEntity<List<Department>> getAllDepartmentsForPatient() {
        return ResponseEntity.ok(departmentRepository.findAll());
    }

    @GetMapping("/schedules/byDepartment")
    public ResponseEntity<?> getSchedulesByDepartment(
            @RequestParam Long departmentId,
            @RequestParam @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) LocalDate date) {
        List<Schedule> schedules = scheduleRepository.findByDepartmentAndDate(departmentId, date);
        return ResponseEntity.ok(schedules);
    }

    @PostMapping("/appointments")
    public ResponseEntity<?> createAppointment(
            @RequestParam Long scheduleId,
            Authentication authentication) {
        User patient = userRepository.findByUsername(authentication.getName());
        Schedule schedule = scheduleRepository.findById(scheduleId)
                .orElseThrow(() -> new RuntimeException("排班不存在"));
        Appointment appointment = new Appointment();
        appointment.setPatient(patient);
        appointment.setDoctor(schedule.getDoctor());
        appointment.setSchedule(schedule);
        appointment.setStatus(Appointment.Status.PENDING);
        Appointment savedAppointment = appointmentRepository.save(appointment);
        Message message = new Message();
        message.setContent("新的预约请求：" + savedAppointment.getId() + "，患者：" + patient.getUsername());
        message.setReceiver(schedule.getDoctor().getUser());
        messageRepository.save(message);
        return ResponseEntity.ok(savedAppointment);
    }

    @GetMapping("/messages")
    public List<Message> getMessages(Authentication authentication) {
        User user = userRepository.findByUsername(authentication.getName());
        return messageRepository.findByReceiverOrderByCreatedAtDesc(user);
    }

    @RestController
    @RequestMapping("/comments")
    @RequiredArgsConstructor  // 自动生成构造函数
    public class CommentController {
        private final CommentRepository commentRepository;
        private final UserRepository userRepository;

        @PostMapping
        public ResponseEntity<Comment> createComment(
                @RequestBody String content,
                Authentication authentication) {
            User user = userRepository.findByUsername(authentication.getName());
            Comment comment = new Comment();
            comment.setUser(user);
            comment.setContent(content);
            return ResponseEntity.ok(commentRepository.save(comment));
        }
    }

    @GetMapping("/medicines")
    public List<Medicine> getAllMedicines() {
        return medicineRepository.findAll();
    }

    @PostMapping("/purchase")
    public ResponseEntity<?> purchaseMedicine(
            @RequestParam Long medicineId,
            @RequestParam int quantity,
            Authentication authentication) {
        User user = userRepository.findByUsername(authentication.getName());
        Medicine medicine = medicineRepository.findById(medicineId)
                .orElseThrow(() -> new RuntimeException("药品不存在"));
        if (medicine.getStock() < quantity) {
            return ResponseEntity.badRequest().body("库存不足");
        }
        medicine.setStock(medicine.getStock() - quantity);
        medicineRepository.save(medicine);
        UserMedicine userMedicine = userMedicineRepository.findByUserAndMedicine(user, medicine)
                .orElse(new UserMedicine(user, medicine, 0));
        userMedicine.setQuantity(userMedicine.getQuantity() + quantity);
        userMedicineRepository.save(userMedicine);
        return ResponseEntity.ok("购买成功");
    }

    @GetMapping("/inventory")
    public List<UserMedicine> getInventory(Authentication authentication) {
        User user = userRepository.findByUsername(authentication.getName());
        return userMedicineRepository.findByUser(user);
    }
}